<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>返回数组中指定元素的下标</title>
</head>
<body>
    <script>
    var arr = ['a', 'b', 'd', 'd', 'c', 'd', 'd'];
    var res = [];
    var indexnum = 0; //统计字母出现的个数
    var num = 0; //原数组的下标
    for (var i = 0; i < arr.length; i++) {   
        num = arr.indexOf('d', 0);    //获得第一个d的下标
        if (num != -1) {    //记录个数   
            res[indexnum] = num;      
            indexnum++;   
        }   
        arr[num] = 'c';
    }
    //遍历数组，输出元素d所在的下标
    for (var i = 0; i < res.length; i++) {   
        document.write(res[i] + ',');
    }
    document.write('</br>' + indexnum); //输出字母出现的个数
    /*
    var arr = ['a', 'b', 'd', 'd', 'c', 'd', 'd'];
        var search = 'd';
        var res = [];
        var i = arr.indexOf(search);
        while (i !== -1) {
            res.push(i);
            i = (i <= 6 ? arr.indexOf(search, i + 1) : -1);
        }
        document.write("元素" + search + '在数组中对应下标：' + res + '<br>d出现的次数:' + res.length);
*/
    </script>
</body>
</html>